package com.tomica.mailsigner.common;

import net.sf.andpdf.pdfviewer.PdfViewerActivity;

import cfca.mobile.keydevice.AudioToken;

import com.entersafe.safeca.Constant;
import com.entersafe.safeca.MyProgressDialog;
import com.entersafe.safeca.P11Other;
import com.tomica.mailsigner.signmail.SignMailActivity;
import com.tomica.mailsigner.signpdf.SignPDFActivity;
import com.tomica.mailsigner.token.Token;
import com.tomica.mailsigner.R;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

/**
 * Main Activity
 * @author TOMICALAB
 *
 */
public class MainActivity extends Activity implements OnClickListener {

	private Button btnEmailSign;

	public Context context;
	public MainModel mModel;
	public Handler handler;
	private Token token;

	public MyProgressDialog progressDialog;
	public Resources res;

	private BroadcastReceiver headSetReceiver = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		context = this;
		res = this.getResources();
		P11Other.audioToken = new AudioToken(this);
		progressDialog = new MyProgressDialog(this);
		
		handler = new Handler(){
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case Constant.SHOWPROGRESSDIALOG:
					Log.e(Constant.Debug, "SHOWPROGRESSDIALOG");
					progressDialog.setShowInfo(res.getString(R.string.inform_tryconnect_init));
					progressDialog.show();
					break;
				case Constant.CLOSEPROGRESSDIALOG:
					progressDialog.dismiss();
					break;
				case Constant.TOKEN_CONNECT_OK:
					
					break;
				case Constant.SHOWERRINFO :
					if (null != msg.obj) {
						if (msg.obj.toString().compareTo(
								res.getString(R.string.inform_handset_connectfail)) == 0) {
							String title, button;
							button = res.getString(R.string.inform_button_OK);
							title = res.getString(R.string.inform_title);
							new Builder(context)
									.setTitle(title)
									.setMessage(msg.obj.toString())
									.setPositiveButton(button,
											new DialogInterface.OnClickListener() {

												@Override
												public void onClick(
														DialogInterface arg0,
														int arg1) {
													// TODO: error handle. finish();
												}
											}).show();
						} else
							showMessage(msg.obj.toString());
					}
					break;
				case 0:

					break;
				default:
					Log.v("Handler", "Default message");
					super.handleMessage(msg);
				}
			}
		};
		
		mModel = new MainModel(this, handler);
		token = new Token(context, handler);

		btnEmailSign = (Button) findViewById(R.id.btnEmailSign);
		btnEmailSign.setOnClickListener(this);


		headSetReceiver = new BroadcastReceiver() {
			public void onReceive(Context context, Intent intent) {
				String action = intent.getAction();
				if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
					// headphone plugged
					if (intent.getIntExtra("state", 0) == 1) {
						Log.i("Handset", "Handset plugin");
						token.tryConnect();

						// headphone unplugged
					} else {
						Log.i("Handset", "Handset plugout");
						token.disConnect();
						// TODO: show dialog to insert AudioPass showDialog(0);

					}
				}
			}
		};
		registerReceiver(headSetReceiver, new IntentFilter(
				Intent.ACTION_HEADSET_PLUG));
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	@SuppressWarnings("deprecation")
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case 0:
			return new AlertDialog.Builder(context)
					.setTitle(res.getString(R.string.inform_title))
					.setMessage(res.getString(R.string.inform_handset_plugout))
					.create();
		}
		return super.onCreateDialog(id);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_settings:
			// Account setting
			Intent intent = new Intent(this, SettingsActivity.class);
			startActivity(intent);
			return true;
		case R.id.action_battery_info:
			Intent bIntent = new Intent(this, BatteryInfoActivity.class);
			startActivity(bIntent);
			return true;
		case R.id.action_change_pin:
			// We will change pin here.
			Intent pinIntent = new Intent(context, ChangePinActivity.class);
			startActivity(pinIntent);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnEmailSign:
			Intent intent = new Intent(context, SignMailActivity.class);
			startActivity(intent);
			Log.v("you're great","");
			break;
		default:
			break;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.i(Constant.Debug, "onDestroy Main screen");
		// disConnect();
		P11Other.audioToken.Release();
		unregisterReceiver(headSetReceiver);
	}
	
	private void showMessage(String msg) {
		if (null == msg || "" == msg)
			return;

		String title, button;
		button = res.getString(R.string.inform_button_OK);
		title = res.getString(R.string.inform_title);
		new Builder(context).setTitle(title).setMessage(msg)
				.setPositiveButton(button, null).show();
	}
	
	public boolean isOnline() {
	    ConnectivityManager cm =
	        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo netInfo = cm.getActiveNetworkInfo();
	    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
	        return true;
	    }
	    return false;
	}
}
